from django.test import TestCase

# Create your tests here.
#验证用户的是否登陆
from django.http import HttpResponseRedirect
from django.urls import reverse

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.exempt_paths = [
            '/login',
            '/admin/',
            '/static/',
        ]

    def __call__(self, request):
        if not self.should_check_login(request):
            return self.get_response(request)
        if not request.user.is_authenticated:
            return HttpResponseRedirect(reverse('login') + f'?next={request.path}')
        return self.get_response(request)

    def should_check_login(self, request):
        path = request.path_info
        return not any(path.startswith(exempt) for exempt in self.exempt_paths)